package com.yangle.frame.common.controller;

import com.yangle.frame.common.utils.DateUtils;
import com.yangle.frame.common.utils.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class FileUploadController {
    //获取上传文件的路径
    @Value("${file.upload.path}")
    private String fileUploadPath;
    @ResponseBody
    @PostMapping("/upload")
    public Map singleFileUpload(@RequestParam("file") MultipartFile file,
                                   HttpServletRequest request) {
        //文件访问地址
        String urlPath="";
//        封装返回结果
        Map map =new HashMap();
        if (file.isEmpty()) {
            map.put("message","不允许空文件上传");
            map.put("statusCode","300");
            map.put("filename","");
            return map;
        }

        try {
            // Get the file and save it somewhere

            String subpath= DateUtils.getDateString();
           String ext= file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
        String uuid=UUID.randomUUID().toString();
           String filePath=fileUploadPath+subpath+ uuid+ext;
            urlPath="images/"+subpath+ uuid+ext;
            FileUtils.uploadFile(file, filePath);


        } catch (IOException e) {
            e.printStackTrace();
            map.put("message","上传失败");
            map.put("statusCode","300");
            map.put("filename","");
            return map;
        }
        map.put("message","文件上传成功");
        map.put("statusCode","200");
        map.put("filename",urlPath);
        return map;
    }



    @ResponseBody
    @RequestMapping("/uploadStatus")
    public Map test(HttpServletRequest request){
        Map map=new HashMap();
        map.put("message","文件上传成功");
        map.put("statusCode","200");
        map.put("filename","");
        return map;
    }

}